package com.drug.mingkang.service.impl;

import com.drug.mingkang.mapper.ManufacturePlanMapper;
import com.drug.mingkang.model.*;
import com.drug.mingkang.permission.model.PerUsers;
import com.drug.mingkang.service.*;
import com.google.gson.internal.$Gson$Preconditions;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.nio.file.Watchable;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 制造计划表(ManufacturePlan)表服务实现类
 *
 * @author makejava
 * @since 2020-08-27 09:12:02
 */
@Service("manufacturePlanService")
public class ManufacturePlanServiceImpl implements ManufacturePlanService {
    @Resource
    private ManufacturePlanMapper manufacturePlanDao;

    @Resource
    private HqPdetailService hqPdetailService;

    @Resource
    private HqDrugmaterialsService hqDrugmaterialsService;

    @Resource
    private HqInventoryService hqInventoryService;

    @Resource
    private HqPlanService hqPlanService;

    @Resource
    HttpSession session;

    @Resource
    private HqWarehousingService hqWarehousingService;
    /**
     * 通过ID查询单条数据 开始制造
     *
     * @param planId 生产计划单主键
     * @return 实例对象
     */
    @Override
    public List<ManufacturePlan> queryById(String planId) {
        Timestamp timestamp = new Timestamp(new Date().getTime());
        String time =timestamp.toString();
        PerUsers perUsers = (PerUsers) session.getAttribute("perUsers");
        //根据计划单id查询制造明细
        List<ManufacturePlan> list = queryByPlanId(planId);
        List<HqPdetail> pdetails;

        List<HqWarehousing> warehousingList = new ArrayList<>();

        List<HqInventory> inventoryList = new ArrayList<>();
        //制造明细表为空时根据计划单id增加制造明细
        if (list.size()<1){
            //修改计划单状态为正在制造
            HqPlan hqPlan = new HqPlan();
            hqPlan.setPlanId(planId);
            hqPlan.setState(70);
            int updateState = this.hqPlanService.update(hqPlan);
            if(updateState>0){
                //查询计划明细
                pdetails = this.hqPdetailService.queryById(planId);
                for (int i=0;i<pdetails.size();i++){
                    ManufacturePlan manufacturePlan = new ManufacturePlan();
                    manufacturePlan.setPlanId(pdetails.get(i).getPlanId());
                    manufacturePlan.setMpTask(pdetails.get(i).getNum());
                    manufacturePlan.setMpFinished("否");
                    manufacturePlan.setMpUnfinished(pdetails.get(i).getNum());
                    manufacturePlan.setMpScheme("继续制造");
                    manufacturePlan.setMpTime(time);
                    manufacturePlan.setIsva("1");
                    manufacturePlan.setDrugId(pdetails.get(i).getDrugId());
                    list.add(manufacturePlan);

                    List<HqDrugmaterials> drugmaterialsList = queryByDrugId(pdetails.get(i).getDrugId());

                    if(drugmaterialsList != null){
                        //原材料id和要用到的原材料数量
                        for (HqDrugmaterials hqDrugmaterials: drugmaterialsList){
                            HqInventory hqInventory = new HqInventory();
                            hqInventory.setMaterialId(hqDrugmaterials.getMaterialId());
                            hqInventory.setInventoryNum(pdetails.get(i).getNum()*hqDrugmaterials.getMaterialsNum());
                            inventoryList.add(hqInventory);
                        }
                    }

                }

                //减少所制造药品所需的原材料数量
                int count = this.hqInventoryService.updateBatch(inventoryList);
                if(count>0){
                    for(int i= 0;i<inventoryList.size();i++){
                        HqInventory hqInventory = this.hqInventoryService.selectMaterialId(inventoryList.get(i).getMaterialId());
                        System.out.println(hqInventory.getInventoryId());
                        HqWarehousing warehousing = new HqWarehousing();
                        warehousing.setInventoryId(hqInventory.getInventoryId());
                        warehousing.setWareNum(inventoryList.get(i).getInventoryNum());
                        warehousing.setState(2);
                        warehousing.setOper(perUsers.getUserName());
                        warehousing.setWareTime(timestamp);
                        warehousingList.add(warehousing);
                    }

                    //批量增加本次原材料出库数据
                    int rows = this.hqWarehousingService.insertBatch(warehousingList);
                    if(rows<0){
                        return list;
                    }
                }


                //增加制造明细后返回所增加的数据
                int row = this.manufacturePlanDao.insertBatch(list);
                if(row > 0){
                    list = queryByPlanId(planId);
                }

            }

        }
        return list;
    }

    /**
     * 获取制造计划单数量
     * @param manufacturePlan
     * @return
     */
    @Override
    public int getCount(ManufacturePlan manufacturePlan) {
        return this.manufacturePlanDao.getCount(manufacturePlan);
    }


    /**
     * 开始质检
     * @param planId
     * @return
     */
    @Override
    public List<ManufacturePlan> getPlanId(String planId) {
        HqPlan hqPlan = this.hqPlanService.queryById(planId);
        //修改计划单状态为质检中
        if(hqPlan.getState()!=80){
            HqPlan plan = new HqPlan();
            plan.setPlanId(planId);
            plan.setState(80);
            this.hqPlanService.update(plan);
        }
        return this.manufacturePlanDao.getPlanId(planId);
    }


    /**
     * 查询所有锁具
     * @param manufacturePlan
     * @return
     */
    @Override
    public List<ManufacturePlan> findAll(ManufacturePlan manufacturePlan) {
        return this.manufacturePlanDao.findAll(manufacturePlan);
    }





    /**
     * 根据药品id查询bom表
     * @param drugId
     * @return
     */
    public List<HqDrugmaterials> queryByDrugId(String drugId){
        return this.hqDrugmaterialsService.queryByDrugId(drugId);
    }


    /**
     * 根据生产计划单主键查询制造计划表
     * @param planId
     * @return
     */
    public List<ManufacturePlan> queryByPlanId(String planId){
        List<ManufacturePlan> list = this.manufacturePlanDao.queryById(planId);
        return list;
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<ManufacturePlan> queryAllByLimit(int offset, int limit) {
        return this.manufacturePlanDao.queryAllByLimit(offset, limit);
    }


    /**
     * 质检完成 入库
     * @param list
     * @param remark
     * @return
     */
    @Override
    public int quality(List<ManufacturePlan> list,String remark) {

        int row = 0;
        PerUsers perUsers = (PerUsers) session.getAttribute("perUsers");
        Timestamp timestamp = new Timestamp(new Date().getTime());
        List<HqInventory> addHqInventories = new ArrayList<>();
        List<HqInventory> updateHqInventoryList = new ArrayList<>();


        //根据制造计划单药品查找库存，有就改，无则加
        for(ManufacturePlan manufacturePlan:list){
            HqInventory hqInventory =  this.hqInventoryService.queryByDrugId(manufacturePlan.getDrugId());
            HqInventory h = new HqInventory();
            h.setRemark(remark);
            h.setDrugId(manufacturePlan.getDrugId());
            if(hqInventory==null){
                h.setOper(perUsers.getUserName());
                h.setOptime(timestamp);
                h.setInventoryNum(manufacturePlan.getMpTask());
                addHqInventories.add(h);
            }else{
                h.setInventoryNum(hqInventory.getInventoryNum()+manufacturePlan.getMpTask());
                updateHqInventoryList.add(h);
            }
        }

        if(addHqInventories.size()>0){
            row += this.hqInventoryService.quality(addHqInventories);
        }else if(updateHqInventoryList.size()>0){
            row += this.hqInventoryService.updateByDrug(updateHqInventoryList);
        }


        //增加完库存后修改计划单状态为已质检入库
        if(row>0){
            HqPlan hqPlan = new HqPlan();
            hqPlan.setPlanId(list.get(0).getPlanId());
            hqPlan.setState(81);
            this.hqPlanService.update(hqPlan);
        }



        return row;
    }

    /**
     * 新增数据
     *
     * @param manufacturePlan 实例对象
     * @return 实例对象
     */
    @Override
    public ManufacturePlan insert(ManufacturePlan manufacturePlan) {
        this.manufacturePlanDao.insert(manufacturePlan);
        return manufacturePlan;
    }

    /**
     * 修改数据
     *
     * @param manufacturePlan 实例对象
     * @return 实例对象
     */
    @Override
    public ManufacturePlan update(ManufacturePlan manufacturePlan) {
        this.manufacturePlanDao.update(manufacturePlan);
        return null;
    }

    /**
     * 通过主键删除数据
     *
     * @param mpId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String mpId) {
        return this.manufacturePlanDao.deleteById(mpId) > 0;
    }


    /**
     * 制造
     * @param list
     * @return
     */
    @Override
    public int updateBatch(List<ManufacturePlan> list) {

        //查询制造计划表是否全部完成
        int state = 0 ;
        for(ManufacturePlan manufacturePlan : list){
            if(manufacturePlan.getMpUnfinished()!=0){
                state += 1;
                break;
            }
        }
        //完成后修改计划单状态为制造完成
        if(state==0){
            HqPlan hqPlan = new HqPlan();
            hqPlan.setState(71);
            hqPlan.setPlanId(list.get(0).getPlanId());
            this.hqPlanService.update(hqPlan);
        }
        return this.manufacturePlanDao.updateBatch(list);
    }
}